package cn.operation.backend.service.baseArea;


import cn.operation.backend.bo.baseArea.BaseAreaBo;
import cn.operation.backend.bo.baseArea.BaseParentAreaBo;
import cn.operation.backend.enums.BaseAreaLevelEnum;
import cn.operation.backend.enums.BaseStatusEnum;
import cn.operation.backend.query.BaseLnLineQueryConditions;
import cn.operation.backend.util.BusinessException;
import cn.operation.backend.util.PageVo;
import cn.operation.base.dto.extdto.baseArea.ScBaseAreaDto;
import cn.operation.base.mapper.custom.ScBaseAreaCustomMapper;
import cn.operation.base.mapper.extmapper.baseArea.ScBaseAreaExpandMapper;
import cn.operation.base.mapper.ScBaseAreaMapper;
import cn.operation.base.mapper.ScBaseLnLineMapper;
import cn.operation.base.model.ScBaseArea;
import cn.operation.base.model.ScBaseAreaExample;
import cn.operation.base.model.ScBaseLnLine;
import cn.operation.base.model.ScBaseLnLineExample;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Felix on 2017/5/31.
 */
@Service
public class BaseAreaServiceImpl implements BaseAreaService {
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseAreaServiceImpl.class);

    @Autowired
    private ScBaseAreaMapper scBaseAreaMapper;

    @Autowired
    private ScBaseAreaCustomMapper scBaseAreaCustomMapper;

    @Autowired
    private ScBaseLnLineMapper lnLineMapper;

    @Autowired
    private ScBaseAreaExpandMapper scBaseAreaExpandMapper;

    @Override
    public List<ScBaseArea> selectAreaListByConditions(PageVo pageVo, BaseAreaBo conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.selectAreaListByConditions params : {}, {}", conditions);
        try {
            String orderByClause = null;
            if (null != pageVo) {
                orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id ASC";
            }
            ScBaseAreaExample example = new ScBaseAreaExample();
            ScBaseAreaExample.Criteria criteria = example.createCriteria();
            criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
            if (null != conditions && null != conditions.getId() && conditions.getId() > 0) {
                criteria.andIdEqualTo(conditions.getId());
            }

            if (null != conditions && StringUtils.isNotBlank(conditions.getCode())) {
                criteria.andCodeEqualTo(conditions.getCode());
            }
            if (null != conditions && StringUtils.isNotBlank(conditions.getName())) {
                criteria.andNameLikeInsensitive("%" + conditions.getName() + "%");
            }
            if (null != conditions && StringUtils.isNotBlank(conditions.getLevel())) {
                criteria.andLevelEqualTo(conditions.getLevel());
            }
            if (null != pageVo) {
                pageVo.setTotalRecord(scBaseAreaMapper.countByExample(example));
                example.setLimitStart(pageVo.getStartIndex());
                example.setLimitEnd(pageVo.getPageSize());
                example.setOrderByClause(orderByClause);
            }
            List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
            /*
			 * List<BaseAreaBO> boList = new ArrayList<>(); for (ScBaseArea area
			 * : list) { ScBaseArea baseArea =
			 * scBaseAreaMapper.selectByPrimaryKey(area.getParentId());
			 * BaseAreaBO bo = new BaseAreaBO(); BeanUtils.copyProperties(area,
			 * bo); if (baseArea != null) bo.setParentName(baseArea.getName());
			 * if (BaseAreaLevelEnum.PROVINCE.getValue().equals(bo.getLevel()))
			 * { bo.setLevel(BaseAreaLevelEnum.PROVINCE.getText()); } else if
			 * (BaseAreaLevelEnum.CITY.getValue().equals(bo.getLevel())) {
			 * bo.setLevel(BaseAreaLevelEnum.CITY.getText()); } else if
			 * (BaseAreaLevelEnum.COUNTY.getValue().equals(bo.getLevel())) {
			 * bo.setLevel(BaseAreaLevelEnum.COUNTY.getText()); }
			 * boList.add(bo); }
			 */
            return list;
        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.selectAreaListByConditions error : ", e);
            throw new BusinessException("查询所有省级区域异常");
        }
    }

    @Override
    public BaseAreaBo selectById(Integer id, String getRidStatus) throws Exception {
        if (id == null) {
            throw new BusinessException("id不能为空！");
        }

        BaseAreaBo baseAreaBo = new BaseAreaBo();

        if (null != getRidStatus) {
            ScBaseArea baseArea = scBaseAreaCustomMapper.selectById(id, getRidStatus);
            if (null != baseArea)
                BeanUtils.copyProperties(baseArea, baseAreaBo);
        } else {
            ScBaseArea baseArea = scBaseAreaMapper.selectByPrimaryKey(id);
            if (null != baseArea)
                BeanUtils.copyProperties(baseArea, baseAreaBo);
        }

        return baseAreaBo;
    }

    @Override
    public List<ScBaseArea> getChildAreaListByIdOrCode(PageVo pageVo, BaseAreaBo baseAreaBo) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.getChildAreaListById params : {}, {}", pageVo, baseAreaBo);
        if (null == baseAreaBo || ((null == baseAreaBo.getId() || baseAreaBo.getId() < 1)
                && (null == baseAreaBo.getCode() || StringUtils.isBlank(baseAreaBo.getCode())))) {
            throw new IllegalArgumentException("参数不能为空");
        }

        try {
            String orderByClause = null;
            if (null != pageVo) {
                orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
            }

            ScBaseAreaExample example = new ScBaseAreaExample();
            if (null != baseAreaBo && null != baseAreaBo.getId() && baseAreaBo.getId() > 0) {
                example.createCriteria().andParentIdEqualTo(baseAreaBo.getId())
                        .andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
            }

            if (null != baseAreaBo && null != baseAreaBo.getCode() && StringUtils.isBlank(baseAreaBo.getCode())) {
                ScBaseArea area = this.selectByCode(baseAreaBo.getCode());
                if (null != area && area.getId() > 0) {
                    example.createCriteria().andParentIdEqualTo(area.getId())
                            .andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
                }
            }

            if (null != pageVo) {
                int count = scBaseAreaMapper.countByExample(example);
                pageVo.setTotalRecord(count);
                example.setLimitStart(pageVo.getStartIndex());
                example.setLimitEnd(pageVo.getPageSize());
            }

            example.setOrderByClause(orderByClause);
            List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
            return list;
        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.getChildAreaListById error : ", e);
            throw new BusinessException("查询子集区域异常");
        }
    }

    @Override
    public List<ScBaseArea> getChildAreaListById(PageVo pageVo, Integer id) throws Exception {
        BaseAreaBo baseAreaBo = new BaseAreaBo();
        baseAreaBo.setId(id);
        return getChildAreaListByIdOrCode(pageVo, baseAreaBo);
    }

    @Override
    public List<BaseAreaBo> getAllProvinceArea() throws Exception {
        ScBaseAreaExample example = new ScBaseAreaExample();
        example.createCriteria().andLevelEqualTo(BaseAreaLevelEnum.PROVINCE.getValue())
                .andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
        List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
        List<BaseAreaBo> listBO = new ArrayList<>();
        for (ScBaseArea scBaseArea : list) {
            BaseAreaBo baseAreaBo = new BaseAreaBo();
            BeanUtils.copyProperties(scBaseArea, baseAreaBo);
            listBO.add(baseAreaBo);
        }
        return listBO;
    }

    @Override
    public List<BaseAreaBo> getAllCityArea() throws Exception {
        ScBaseAreaExample example = new ScBaseAreaExample();
        example.createCriteria().andLevelEqualTo(BaseAreaLevelEnum.CITY.getValue())
                .andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
        List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
        List<BaseAreaBo> listBO = new ArrayList<>();
        for (ScBaseArea scBaseArea : list) {
            BaseAreaBo baseAreaBo = new BaseAreaBo();
            BeanUtils.copyProperties(scBaseArea, baseAreaBo);
            listBO.add(baseAreaBo);
        }
        return listBO;
    }

    @Override
    public List<ScBaseArea> getCityAndCountyAreaList(PageVo pageVo, BaseAreaBo baseAreaBo) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.getCityAndCountyAreaList params : {}, {}", pageVo, baseAreaBo);
        if (null == baseAreaBo || ((null == baseAreaBo.getId() || baseAreaBo.getId() < 1)
                && (null == baseAreaBo.getCode() || StringUtils.isBlank(baseAreaBo.getCode())))) {
            throw new IllegalArgumentException("参数不能为空");
        }

        ScBaseArea area = null;
        try {

            if (null != baseAreaBo && null != baseAreaBo.getId() && baseAreaBo.getId() > 0) {
                area = scBaseAreaMapper.selectByPrimaryKey(baseAreaBo.getId());
            }

            if (null != baseAreaBo && StringUtils.isNotBlank(baseAreaBo.getCode())) {
                area = this.selectByCode(baseAreaBo.getCode());
            }
        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.getCityAndCountyAreaList error : ", e);
            throw new BusinessException("根据省级区域查询其下市级区域和县级区域异常");
        }

        if (null == area || null == area.getLevel() || !area.getLevel().equals(BaseAreaLevelEnum.PROVINCE.getValue())) {
            throw new IllegalAccessException("该省份不存在");
        }

        List<ScBaseArea> list = null;

        try {
            list = new ArrayList<ScBaseArea>();
            String orderByClause = null;
            if (null != pageVo) {
                orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " id DESC";
            }

            ScBaseAreaExample example = new ScBaseAreaExample();
            example.createCriteria().andPathLikeInsensitive("%" + area.getCode() + "%")
                    .andLevelNotEqualTo(BaseAreaLevelEnum.PROVINCE.getValue());

            if (null != pageVo) {
                int count = scBaseAreaMapper.countByExample(example);
                pageVo.setTotalRecord(count);
                example.setLimitStart(pageVo.getStartIndex());
                example.setLimitEnd(pageVo.getPageSize());
            }
            example.setOrderByClause(orderByClause);
            list = scBaseAreaMapper.selectByExample(example);
        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.getCityAndCountyAreaList error : ", e);
            throw new BusinessException("根据省级区域查询其下市级区域和县级区域异常");
        }

        return list;
    }

    @Override
    public List<ScBaseArea> queryStartArea(PageVo pageVo, BaseLnLineQueryConditions conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.queryStartArea params : {}, {}", pageVo, conditions);
        List<ScBaseArea> list = new ArrayList<>();
        if (StringUtils.isNotBlank(conditions.getAreaKeyword())) {
            list = scBaseAreaMapper.queryStartArea("%" + conditions.getAreaKeyword() + "%", null, null);
        } else {
            list = scBaseAreaMapper.queryStartArea(null, null, null);
        }
        return list;
    }

    @Override
    public Integer queryStartAreaCount(BaseLnLineQueryConditions conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.queryStartAreaCount params : {}, {}", conditions);
        return scBaseAreaMapper.queryStartAreaCount("%" + conditions.getAreaKeyword() + "%");
    }

    @Override
    public List<ScBaseArea> queryEndProvince(PageVo pageVo, BaseLnLineQueryConditions conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.queryEndProvince params : {}, {}", pageVo, conditions);
        ScBaseLnLineExample example = new ScBaseLnLineExample();
        example.createCriteria().andStartAreaIdEqualTo(conditions.getStartAreaId())
                .andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
        List<ScBaseLnLine> list = lnLineMapper.selectByExample(example);
        List<ScBaseArea> areaList = new ArrayList<ScBaseArea>();
        Set<ScBaseArea> set = new HashSet<ScBaseArea>();
        for (ScBaseLnLine lnLine : list) {
            if (lnLine.getEndAreaId() != null) {
                ScBaseArea area = getProvinceArea(scBaseAreaMapper.selectByPrimaryKey(lnLine.getEndAreaId()));
                if (set.add(area)) {
                    areaList.add(area);
                }
            }
        }
        return areaList;
    }

    @Override
    public Integer queryEndProvinceCount(BaseLnLineQueryConditions conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.queryEndProvinceCount params : {}, {}", conditions);
        List<ScBaseArea> list = scBaseAreaMapper.queryEndProvince(conditions.getStartAreaId());
        List<Integer> idList = new ArrayList<>();
        for (ScBaseArea ar : list) {
            ScBaseArea scBaseArea = getProvinceArea(ar);
            if (scBaseArea.getCode() != null) {
                idList.add(scBaseArea.getId());
            }
        }
        return scBaseAreaMapper.queryPrivinceListCount(idList);
    }

    @Override
    public List<ScBaseArea> queryEndArea(PageVo pageVo, BaseLnLineQueryConditions conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.queryEndProvince params : {}, {}", pageVo, conditions);
        List<ScBaseArea> list = scBaseAreaMapper.queryEndArea(conditions.getStartAreaId(),
                "%" + conditions.getEndProvinceId() + "%", null, null);
        return list;
    }

    @Override
    public Integer queryEndAreaCount(BaseLnLineQueryConditions conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.queryEndProvinceCount params : {}, {}", conditions);
        return scBaseAreaMapper.queryEndAreaCount(conditions.getStartAreaId(),
                "%" + conditions.getEndProvinceId() + "%");
    }

    @Override
    public List<ScBaseArea> selectAllCity(String city) throws Exception {
        ScBaseAreaExample example = new ScBaseAreaExample();
        example.createCriteria().andLevelEqualTo(city).andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
        List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
        return list;
    }

    public ScBaseArea getProvinceArea(ScBaseArea area) throws Exception {
        ScBaseArea scBaseArea = new ScBaseArea();
        if (!area.getLevel().equals(BaseAreaLevelEnum.PROVINCE.getValue()) && area.getLevel() != null) {
            String[] path = area.getPath().split(",");
            ScBaseAreaExample example = new ScBaseAreaExample();
            example.createCriteria().andCodeEqualTo(path[0]);
            List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
            scBaseArea = list.get(0);
        } else {
            BeanUtils.copyProperties(area, scBaseArea);
        }
        return scBaseArea;
    }

    @Override
    public ScBaseArea updateArea(BaseAreaBo areaBO) throws Exception {

        ScBaseArea newArea = new ScBaseArea();
        BeanUtils.copyProperties(areaBO, newArea);
        // 验证数据
        validateArea(newArea);

        // 原来的区域
        BaseAreaBo oldAreaBO = selectById(newArea.getId(), BaseStatusEnum.DELETE.getValue());
        if (null == oldAreaBO) { // 判断对象是否存在
            throw new BusinessException("区域数据不存在");
        }

        // 判断原来的code 是否和新修改的code一样
        if (!oldAreaBO.getCode().equals(newArea.getCode())) {
            Integer codeCount = scBaseAreaCustomMapper.countByCode(newArea.getCode(), BaseStatusEnum.DELETE.getValue());
            if (codeCount >= 1) {
                throw new BusinessException("区域编码已存在");
            }
        }

        // 进行上级区域数据判断
        if (null != newArea.getParentId()) {
            // 判断是否和原来相同
            if (oldAreaBO.getParentId().intValue() != newArea.getParentId().intValue()) { // 不相同
                StringBuffer path = new StringBuffer();
                // 上级区域数据
                ScBaseArea fristParentArea = scBaseAreaCustomMapper.selectById(newArea.getParentId(),
                        BaseStatusEnum.DELETE.getValue());
                if (null == fristParentArea) {
                    throw new BusinessException("上级区域数据不存在");
                }
                // 添加到路径中
                path.append(fristParentArea.getId());

                // 判断是否有还有上级
                if (null != fristParentArea.getParentId() && fristParentArea.getParentId().intValue() != 0) {
                    path.append(",");
                    path.append(fristParentArea.getParentId());
                }
                newArea.setPath(path.toString()); // 添加父级别路径
            } else { // 相同
                newArea.setPath(oldAreaBO.getPath()); // 设置为原来的路径
            }
        }

        newArea.setGmtCreate(oldAreaBO.getGmtCreate());
        newArea.setGmtModified(new Date());
        newArea.setStatus(newArea.getStatus() == null ? oldAreaBO.getStatus() : newArea.getStatus());
        scBaseAreaMapper.updateByPrimaryKey(newArea);
        return newArea;
    }

    @Override
    public ScBaseArea selectByCode(String code) {
        return scBaseAreaCustomMapper.selectByCode(code);
    }

    @Override
    public List<ScBaseArea> selectAreByIdOrCode(BaseAreaBo conditions) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.selectAreByIdOrCode params : {}", conditions);

        if (null == conditions || ((null == conditions.getId() || conditions.getId() < 1)
                && (null == conditions.getCode() || StringUtils.isBlank(conditions.getCode())))) {
            throw new IllegalArgumentException("参数不能为空");
        }
        try {
            ScBaseAreaExample example = new ScBaseAreaExample();
            ScBaseAreaExample.Criteria criteria = example.createCriteria();
            criteria.andStatusEqualTo(BaseStatusEnum.RIGHT.getValue());
            if (StringUtils.isNotBlank(conditions.getCode())) {
                criteria.andCodeEqualTo(conditions.getCode());
            }
            if (null != conditions.getId() && conditions.getId() > 0) {
                criteria.andIdEqualTo(conditions.getId());
            }

            List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
            return list;
        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.selectAreByIdOrCode error : ", e);
            throw new BusinessException("根据id或code查询区域详情异常");
        }
    }

    @Override
    public void addArea(BaseAreaBo areaBO) {

        ScBaseArea area = new ScBaseArea();
        BeanUtils.copyProperties(areaBO, area);
        // 校验对象
        validateArea(area);

        Integer codeCount = scBaseAreaCustomMapper.countByCode(area.getCode(), BaseStatusEnum.DELETE.getValue());
        if (codeCount >= 1) { // 判断区域编码是否存在
            throw new BusinessException("区域编码已存在");
        }

        // 进行上级区域数据判断
        if (null != area.getParentId()) {
            StringBuilder path = new StringBuilder();
            // 上级区域数据
            ScBaseArea fristParentArea = scBaseAreaCustomMapper.selectById(area.getParentId(),
                    BaseStatusEnum.DELETE.getValue());
			/*if (null == fristParentArea) {
				throw new BusinessException("上级区域数据不存在");
			}*/
            if (fristParentArea != null) {
                // 添加到路径中
                path.append(fristParentArea.getId());
                // 判断是否有还有上级
                if (null != fristParentArea.getParentId()) {
                    path.append(",");
                    path.append(fristParentArea.getParentId());
                }
                area.setPath(path.toString()); // 添加父级别路径
            }else{
                //如果parentId=0代表省级的区域时，设置默认的path为code
                area.setPath(area.getCode());
            }
        }
        if (area != null && area.getStatus() == null) {
            area.setStatus(BaseStatusEnum.RIGHT.getValue());
        }
        if (area.getGmtCreate() == null) {
            area.setGmtCreate(new Date());
        }
        if (area.getGmtModified() == null) {
            area.setGmtModified(new Date());
        }
        scBaseAreaMapper.insert(area);
    }

    @Override
    public void deleteByIds(String ids) {
        List<String> list = Arrays.asList(ids.split(","));
        scBaseAreaCustomMapper.deleteByIds(list, BaseStatusEnum.DELETE.getValue());
    }

    @Override
    public List<ScBaseArea> list(BaseAreaBo areaBO) {
        return scBaseAreaCustomMapper.selectChildArea(areaBO.getId(), BaseStatusEnum.RIGHT.getValue());
    }

    @Override
    public List<BaseAreaBo> getAreaTree() {
        // 查询省级
        List<ScBaseArea> areaList = scBaseAreaCustomMapper.selectChildArea(null, BaseStatusEnum.RIGHT.getValue());

        List<BaseAreaBo> areaBOList = new ArrayList<>(); // 省级BO list
        for (ScBaseArea scBaseArea : areaList) {
            BaseAreaBo areaBO = new BaseAreaBo();
            BeanUtils.copyProperties(scBaseArea, areaBO);

            // 获取市级
            List<ScBaseArea> chilAreaList = scBaseAreaCustomMapper.selectChildArea(areaBO.getId(),
                    BaseStatusEnum.RIGHT.getValue());
            List<BaseAreaBo> chilAreaBOList = new ArrayList<>(); // 市级BO list
            for (ScBaseArea chilArea : chilAreaList) {
                BaseAreaBo chilAreaBO = new BaseAreaBo();
                BaseAreaBo parentAreaBO = new BaseAreaBo();
                BeanUtils.copyProperties(chilArea, chilAreaBO);
                BeanUtils.copyProperties(areaBO, parentAreaBO);
                chilAreaBO.setParentAreaBO(parentAreaBO);
                chilAreaBOList.add(chilAreaBO);
            }

            areaBO.setChildAreaBOList(chilAreaBOList);
            areaBOList.add(areaBO);
        }

        return areaBOList;
    }

    /**
     * @Title: validateArea @Description: 校验区域 @param @param area @return void
     * 返回类型 @throws
     */
    private void validateArea(ScBaseArea area) {

        if (StringUtils.isBlank(area.getCode())) { // 判断区域编码是否为空
            throw new BusinessException("区域编码不能为空");
        } else if (StringUtils.isBlank(area.getName())) { // 判断区域名称是否为空
            throw new BusinessException("区域名称不能为空");
        } else if (StringUtils.isBlank(area.getSname())) { // 判断区域简称是否为空
            throw new BusinessException("区域简称不能为空");
        } else if (StringUtils.isBlank(area.getLevel())) { // 判断区域等级是否为空
            throw new BusinessException("区域等级不能为空");
        } else if (StringUtils.isBlank(area.getPinyin())) { // 判断区域拼音是否为空
            throw new BusinessException("区域拼音不能为空");
        } else if (StringUtils.isBlank(area.getInitialWords())) { // 判断区域拼音首字母是否为空
            throw new BusinessException("区域拼音首字母不能为空");
        }

    }

  /*  @Override
    public List<ScBaseAreaDto> selectTreeByparentId(BaseAreaBo baseAreaBo) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.selectTreeByparentId params : {}", baseAreaBo);

        if (null == baseAreaBo || ((null == baseAreaBo.getId() ||
                baseAreaBo.getId() < 1) && (null == baseAreaBo.getCode() ||
                StringUtils.isBlank(baseAreaBo.getCode())))) {
            throw new
                    IllegalArgumentException("参数不能为空");
        }

        try {

            ScBaseArea area = null;
            if (null != baseAreaBo && null != baseAreaBo.getId() &&
                    baseAreaBo.getId() > 0) {
                area = scBaseAreaMapper.selectByPrimaryKey(baseAreaBo.getId());
            }

            if (null != baseAreaBo && StringUtils.isNotBlank(baseAreaBo.getCode())) {
                area = this.selectByCode(baseAreaBo.getCode());
            }

            if (null != area && area.getId() > 0) {
                List<ScBaseAreaDto> areaList = scBaseAreaExpandMapper.selectTreeById();
                return areaList;
            }

        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.selectTreeByparentId error : ", e);
            throw new BusinessException("递归查询下级区域异常");
        }

        return null;
    }
*/
    @Override
    public BaseParentAreaBo getParenAreaList(BaseAreaBo baseAreaBo) throws Exception {
        LOGGER.info("BaseAreaServiceImpl.getParenArea params : {}", baseAreaBo);

        BaseParentAreaBo baseParentAreaBo = null;

        if (null == baseAreaBo || ((null == baseAreaBo.getId() || baseAreaBo.getId() < 1)
                && (null == baseAreaBo.getCode() || StringUtils.isBlank(baseAreaBo.getCode())))) {
            throw new IllegalArgumentException("参数不能为空");
        }

        ScBaseArea area = null;
        if (null != baseAreaBo && null != baseAreaBo.getId() && baseAreaBo.getId() > 0) {
            area = scBaseAreaMapper.selectByPrimaryKey(baseAreaBo.getId());
        }

        if (null != baseAreaBo && StringUtils.isNotBlank(baseAreaBo.getCode())) {
            area = this.selectByCode(baseAreaBo.getCode());
        }

        if (null == area || null == area.getId() || area.getId() < 1) {
            throw new IllegalArgumentException("没找到区域信息");
        }

        try {
            List<BaseParentAreaBo> areaList = new ArrayList<>();
            if (null != area && area.getId() > 0) {
                if (null != area.getPath() && StringUtils.isNoneBlank(area.getPath())) {
                    String path = area.getPath();
                    String[] paths = path.split(",");
                    for (String code : paths) {
                        ScBaseArea a = this.selectByCode(code);
                        BaseParentAreaBo b = new BaseParentAreaBo();
                        BeanUtils.copyProperties(a, b);
                        areaList.add(b);
                    }
                }
            }

            if (areaList!=null&&areaList.size()>0) {
                int size = areaList.size();
                for (int i = size - 1; i >= 0; i--) {
                    if (i == size - 1) {
                        baseParentAreaBo = areaList.get(i);
                    }
                    if (i - 1 >= 0) {
                        BaseParentAreaBo parentArea = areaList.get(i - 1);
                        parentArea.setChildArea(baseParentAreaBo);
                        baseParentAreaBo = parentArea;
                    }
                }
            }

            return baseParentAreaBo;

        } catch (Exception e) {
            LOGGER.error("BaseAreaServiceImpl.getParenArea error : ", e);
            throw new BusinessException("查询上级区域异常");
        }
    }

    @Override
    public List<ScBaseArea> getCityAreaByParentId(Integer id) {
        LOGGER.info("BaseAreaServiceImpl.getParenArea params : {}", id);

        List<ScBaseArea> list = scBaseAreaCustomMapper.selectByParentId(id);

        return list;
    }

    @Override
    public List<ScBaseArea> getCountyArea(Integer id) {
        LOGGER.info("BaseAreaServiceImpl.getCountyArea params : {}", id);

        List<ScBaseArea> list = scBaseAreaCustomMapper.selectCountryByParentId(id);
        return list;
    }

    /**
     * 返回tree对象
     */
    @Override
    public List<ScBaseArea> selectTree(Integer id) {
        LOGGER.info("BaseAreaServiceImpl.selectTree params : {}", id);
        if (null == id || 0 == id) {
            id = 0;
            List<ScBaseArea> list = scBaseAreaCustomMapper.selectAllProvince(id);
            return list;
        }
        List<ScBaseArea> list = scBaseAreaCustomMapper.selectCityAndCounty(id);

        return list;
    }

    /**
     * 获取所有区域的级别
     *
     * @return
     */
    @Override
    public List<ScBaseArea> selectAllAreaLevel() {
        LOGGER.info("BaseAreaServiceImpl.selectAllAreaLevel:");
        List<ScBaseArea> list = scBaseAreaCustomMapper.selectAllAreaLevel();
        return list;
    }

    /**
     * 查询所有市级区域
     */
	@Override
	public List<ScBaseArea> findAllCiyt() {
		LOGGER.info("BaseAreaServiceImpl.findAllCiyt:");
		ScBaseAreaExample example = new ScBaseAreaExample();
		example.createCriteria().andLevelEqualTo(BaseAreaLevelEnum.CITY.getValue());
		List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
//		List<ScBaseArea> = 
		
		return list;
	}

    @Override
    public List<ScBaseArea> queryStartCity(Integer areaKeyword) throws Exception{
	    LOGGER.info("BaseAreaServiceImpl.queryStartCity: [] param" +areaKeyword);
	    try {
            ScBaseAreaExample example=new ScBaseAreaExample();
            ScBaseAreaExample.Criteria criteria = example.createCriteria().andParentIdEqualTo(areaKeyword);
            List<ScBaseArea> list = scBaseAreaMapper.selectByExample(example);
            return list;
        }catch (Exception e){
            LOGGER.error("BaseAreaServiceImpl.queryStartCity error : ", e);
            throw new BusinessException("查询下级区域异常");
        }
    }
}
